import os
import time

import pyautogui
import win32api
import win32con
import win32gui
from selenium.webdriver.common.by import By

from libs import config
from libs.action import WebDriverAction
from libs.game import Game
from libs.log import Log
from libs.task_helper import TaskHelper
from libs.window import AdsWindow
import pygetwindow as gw


def active_window():
    # 获取所有打开的窗口
    print(driver.title)
    windows = gw.getWindowsWithTitle(driver.title)
    print(len(windows))

    # 找到并激活窗口
    if windows:
        for window in windows:
            hwnd = window._hWnd
            if window.left == 920:
                # 如果窗口被最小化，先恢复窗口
                if window.isMinimized:
                    window.restore()

                    # 强制将窗口置于最前面
                    try:
                        # 通过 win32api 强制激活窗口
                        win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)  # 恢复窗口（如果被最小化）
                        win32gui.SetForegroundWindow(hwnd)  # 将窗口置于前台
                        win32api.SetCursorPos((100, 100))  # 你可以设置鼠标位置，使其不会被某些应用挡住
                    except Exception as e:
                        print(f"无法将窗口置于前台: {e}")

                time.sleep(1)
                if not window.isActive:
                    # 激活窗口
                    window.activate()
                break

def find_and_click(text, seconds=3):
    log.debug_start(f'find button [{text}]...')
    button = action.find_element(By.XPATH, f"//span[text()='{text}']/parent::button",
                                             'RoninLogin', seconds)
    if button:
        button.click()
        log.debug_end('click')
        time.sleep(1)
        return True
    else:
        log.debug_end('fail')
        return False


if __name__ == "__main__":
    parser = TaskHelper.default_args_parser('Wine')
    args = parser.parse_args()
    task_helper = TaskHelper.from_args(args)

    user_id = args.user_id
    log = Log(user_id)
    driver = AdsWindow(user_id).open(True, offset_x=920)
    game = Game(driver, user_id)
    action = WebDriverAction(driver)

    game.enter_game(try_times=1)
    log.debug('wait 3 seconds')
    for _ in range(2):
        try:
            active_window()
            break
        except:
            continue

    time.sleep(3)
    if find_and_click('Connect with Ronin', 10):
        if find_and_click('Ronin wallet extension', 10):
            time.sleep(3)
            current_dir = os.path.dirname(os.path.abspath(__file__))
            ronin_wallet_path = os.path.join(current_dir, 'images', 'wallet_pass_input.png')
            ronin_wallet = None
            # 登录
            for _ in range(10):
                try:
                    ronin_wallet = pyautogui.locateOnScreen(ronin_wallet_path)
                except:
                    time.sleep(1)
                    continue

                break
            # 设置目标输入框位置，假设输入框位于目标位置下方一定的像素
            print('pass_input', ronin_wallet)
            if ronin_wallet:
                input_box_location = (ronin_wallet[0] - 60, ronin_wallet[1] + 10)
            else:
                input_box_location = (1550, 695)

            # 将鼠标移动到输入框
            pyautogui.moveTo(input_box_location)

            # 点击输入框
            pyautogui.click()

            # 等待页面响应
            time.sleep(1)

            # 输入密码并按回车
            wallet_pass = config.get_env('wallet_pass')
            pyautogui.write(wallet_pass)  # 输入密码
            pyautogui.press('enter')  # 按下回车键
            sign_button = None
            for _ in range(10):
                sign_button_image = os.path.join(current_dir, 'images', 'ronin_wallet_sign.png')
                try:
                    sign_button = pyautogui.locateOnScreen(sign_button_image)
                except:
                    time.sleep(1)
                    continue
                break
            print('sign_button', sign_button)
            # 将鼠标移动到签名按钮
            if sign_button:
                pyautogui.moveTo(sign_button[0]+88, sign_button[1] + 28)
            else:
                pyautogui.moveTo(1740, 1050)

            # 点击
            pyautogui.click()

            time.sleep(10)

            AdsWindow(user_id).close()
            task_helper.task_success()

